package com.fingard.crypto;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

import com.fingard.text.StringHelper;

public class DigestHelper {
	
	/**产生文件的MD5摘要*/
	public static byte[] cryptoMD5FromFile(String p_inFilePath) throws Exception{
		FileInputStream inStream = null;
		try{
			MessageDigest md5Algorithm = MessageDigest.getInstance("MD5");
			inStream = new FileInputStream(p_inFilePath);
			byte[] buffer = new byte[256000];
			int readLen = 0;
			while(true){
				readLen = inStream.read(buffer,0,buffer.length);
				if(readLen <= 0){
					break;
				}
				md5Algorithm.update(buffer, 0, readLen);
			}
			return md5Algorithm.digest();
		}
		catch(Exception ex){
			throw ex;
		}
		finally{
			if(inStream != null){
				inStream.close();
			}
		}
    }
	
	public static byte[] cryptoMD5(byte[] p_bytes) throws Exception{
		MessageDigest md5Algorithm = MessageDigest.getInstance("MD5");
		md5Algorithm.update(p_bytes, 0, p_bytes.length);
		return md5Algorithm.digest();
    }
	
	/**生成MD5摘要，返回16进制表示的字符串*/
	public static String cryptoMD5RetHexStr(byte[] p_bytes) throws Exception{
		byte[] resultBytes = cryptoMD5(p_bytes);
		return StringHelper.bytesToHexString(resultBytes);
    }
	
	/**生成SHA1摘要*/
	public static byte[] cryptoSHA1(byte[] p_bytes) throws Exception{
		MessageDigest sha1Algorithm = MessageDigest.getInstance("SHA1");
		sha1Algorithm.update(p_bytes, 0, p_bytes.length);
		return sha1Algorithm.digest();
    }
	
	/**生成SHA1摘要，返回16进制表示的字符串*/
	public static String cryptoSHA1RetHexStr(byte[] p_bytes) throws Exception{
		byte[] resultBytes = cryptoSHA1(p_bytes);
		return StringHelper.bytesToHexString(resultBytes);
    }

	/**
	 * 产生文件的MD5摘要
	 * @param filePath
	 * @return
	 */
	public static String cryptoMD5ByFilePath(String filePath){
		File file=new File(filePath);
		FileInputStream fis=null;
		try {
			MessageDigest mdg=MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer=new byte[2048];
			int length=-1;
			while ((length=fis.read(buffer))!=-1){
				mdg.update(buffer,0,length);
			}
			byte[] bytes = mdg.digest();
			return StringHelper.bytesToHexString(bytes);
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			try {
				if(fis!=null){
					fis.close();
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return null;
	}
}
